package com.sinbad.interview.solution.question01.case02;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 方法2：按固定大小分块读取
 *
 * @author sinbad.cheng
 * @since 2025-04-14 16:45
 */
public class ChunkedFileReader {
    private static final int CHUNK_SIZE = 10 * 1024 * 1024; // 10MB

    public static void processLargeFile(String filePath) throws IOException {
        try (RandomAccessFile file = new RandomAccessFile(filePath, "r");
             FileChannel channel = file.getChannel()) {

            long fileSize = channel.size();
            long position = 0;

            while (position < fileSize) {
                long remaining = fileSize - position;
                int chunk = (int) Math.min(CHUNK_SIZE, remaining);

                MappedByteBuffer buffer = channel.map(
                        FileChannel.MapMode.READ_ONLY, position, chunk
                );

                processChunk(buffer);
                position += chunk;
            }
        }

    }


    private static void processChunk(MappedByteBuffer buffer) {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        String chunkData = new String(bytes); // 注意处理编码和断行
        // 自定义处理逻辑
        System.out.println(chunkData);
    }

    public static void main(String[] args) throws IOException {
        processLargeFile("numbers.txt");
    }

}
